package main

import (
	"database/sql"
	"flag"
	"fmt"
	"image"
	_ "image/jpeg"
	"io/ioutil"
	"log"
	"os"
	"strconv"
	"strings"
	"time"
)

var count = 0

func fixFiledImg() {
	logName := time.Now().Format("2006-01-02")
	file, _ := os.OpenFile("./log/error"+logName+".log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) //打开日志文件，不存在则创建
	defer file.Close()

	log.SetOutput(file)

	s := 317440
	flag.IntVar(&s, "s", 0, "refresh now")
	flag.Parse()

	mDB.getPicsFix2()
	mDB.getPicsFix()

	wait := make(chan bool, 8)

	for {
		list := mDB.GetFixMovies(s)
		if len(list) <= 0 {
			break
		}

		s += 3000

		for _, cid := range list {
			wait <- true
			go func(cid string) {
				shot := cid[:3]
				if shot == "con" {
					shot = cid[:4]
				}
				path := "./dmm/movies/" + shot + "/" + cid + "/"
				fixFiledImgInMovie(path, cid)
				<-wait
			}(cid)
		}
		log.Println(count, "next start at ", s)
	}

	log.Println("FixFiledImg Finished")
}

func fixFiledImgInMovie(path, cid string) {
	files, err := ioutil.ReadDir(path)
	if err != nil {
		log.Println(err)
		return
	}
	fullCid := ""
	coverCid := ""

	for _, img := range files {
		count++
		name := img.Name()
		jp := strings.Index(name, "jp-")
		if fullCid == "" {
			if jp != -1 {
				fullCid = name[:jp]
			}
		}

		// 图片过小或者损坏则重下
		if img.Size() > 0 {
			fmt.Println(name, img.Size())

			opfile, err := os.Open(path + name)
			if err != nil {
				continue
			}
			if _, _, err = image.Decode(opfile); err == nil {
				opfile.Close()
				continue
			} else {
				opfile.Close()
				log.Println(name, err)
			}
		}

		os.Remove(path + name)
		if jp != -1 {
			af := name[jp+3 : len(name)-4]
			nu, er := strconv.Atoi(af)
			if er != nil {
				log.Println(er)
				continue
			}
			mDB.UpdatePicFix(cid + "-" + strconv.Itoa(nu-1))
		} else {
			coverCid = name[:len(name)-6]
		}
		log.Println(name, "size", img.Size())
	}

	if coverCid != "" {
		log.Println(coverCid, "|", fullCid)
		if fullCid == "" {
			// 未知，删图，删记录，重置影片，重新下
			mDB.UptMovieFilled(4, cid)
			mDB.UpdatePicFix2(2, "", cid+"ps", cid+"ps-err")
			mDB.UpdatePicFix2(2, "", cid+"pl", cid+"pl-err")
			log.Println("coverCid - 1", cid)
		} else if fullCid == coverCid {
			// 正确，只是重下
			mDB.UpdatePicFix(cid + "ps")
			mDB.UpdatePicFix(cid + "pl")
			log.Println("coverCid - 2", cid, fullCid)
		} else {
			// 不同，改路径，重下
			url := "https://pics.dmm.co.jp/digital/video/" + fullCid + "/" + fullCid + "ps.jpg"
			url2 := "https://pics.dmm.co.jp/digital/video/" + fullCid + "/" + fullCid + "pl.jpg"
			mDB.UpdatePicFix2(0, url, cid+"ps", cid+"ps")
			mDB.UpdatePicFix2(0, url2, cid+"pl", cid+"pl")
			log.Println("coverCid - 3", cid, fullCid)
		}
	}
}

func fixSuffix() {
	//<=100567

	var updateStmt *sql.Stmt
	var uqueryStmt *sql.Stmt
	conn := mDB.getConn()
	if stmt, err := conn.Prepare("UPDATE pics SET `mark`=? WHERE `mark`=?"); err == nil {
		updateStmt = stmt
	} else {
		panic(err.Error())
	}

	if stmt, err := conn.Prepare("SELECT `mark` FROM pics WHERE `id`>? AND `id`<= 100567 ORDER BY id LIMIT 3000"); err == nil {
		uqueryStmt = stmt
	} else {
		panic(err.Error())
	}

	for index := 0; index < 101567; index += 3000 {
		rows, err := uqueryStmt.Query(index)
		if err != nil {
			//log.Println(err)
			return
		}

		var mark string
		for rows.Next() {
			rows.Scan(&mark)

			i := strings.Index(mark, "-")
			if i == -1 {
				log.Println("skip", mark)
				continue
			}

			n, _ := strconv.Atoi(mark[i+1:])
			newMark := mark[0:i+1] + strconv.Itoa(n-1)

			_, err = updateStmt.Exec(newMark, mark)
			log.Println(mark, newMark)
		}
	}
	log.Println("Finished")
}
